<template>
  <a-card :bordered="false">
      <a-form :form="form">
      
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="地址">
          <a-input placeholder="请输入地址" v-decorator="['oilAddress', {rules: [{required: true, message: '请输入地址'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="坐标">
            <a-input v-decorator="['lat', {}]" style="width:30%;margin-right:5%;" :readonly="true"/>
            <a-input v-decorator="['lng', {}]" style="width:30%;margin-right:8%;" :readonly="true"/>
            <a-button @click="handleResetP" style="margin-right:3%;">重置</a-button>
            <a-button type="primary" @click="handleAdd">位置</a-button>
        </a-form-item>
        <a-form-item label="加油站图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            :action="uploadAction"
            :data="{'isup':1}"
            :headers="headers"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="picUrl" :src="getAvatarView()" alt="加油站图片" style="height:104px;max-width:300px"/>
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="电话">
          <a-input placeholder="请输入电话" v-decorator="['phone', {rules: [{required: true, message: '请输入电话!'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="标签">
          <a-tag  v-for="(item, key) in model.list" :key="key" :value="item.id" 
          color="#108ee9" closable @close="closeOilLabel(item.id)">{{item.oilLabel}}</a-tag>
          <a-input
            v-if="inputVisible"
            ref="input"
            type="text"
            size="small"
            :style="{ width: '78px' }"
            :value="inputValue"
            @change="handleInputChange"
            @blur="handleInputConfirm"
            @keyup.enter="handleInputConfirm"
          />
          <a-tag v-else @click="showInput" style="background: #fff; borderStyle: dashed;">
            <a-icon type="plus" /> 新标签
          </a-tag>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label=" ">
          <a-button style="margin-right:5px;">返回</a-button>
          <a-button @click="saveOilConf" type="primary">保存</a-button>
        </a-form-item>
      </a-form>
    
      <oil-conf-modal ref="modalForm" @ok="getP"></oil-conf-modal>
  </a-card>
</template>

<script>
  import pick from 'lodash.pick'
  import moment from 'moment'
  import Vue from 'vue'
  // 引入搜索部门弹出框的组件
  import { httpAction } from '@/api/manage'
  import OilConfModal from './modules/OilConfModal'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { addOilConf } from '@/api/api' 
  export default {
    name: "OilConfList",
    mixins:[JeecgListMixin],
    components: {
      OilConfModal
    },
    data () {
      return {
        description: '加油站配置管理页面',
        picUrl: "",
        inputVisible: false,
        inputValue: '',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        uploadLoading:false,
        confirmLoading: false,
        columns:[],
        headers:{},
        model: {},
        
        form:this.$form.createForm(this),
        url: {
          fileUpload: window._CONFIG['domianURL']+"/sys/common/upload",
          imgerver: window._CONFIG['domianURL']+"/sys/common/view",
          list: "/lww/oilConf/list",
          add: "/lww/oilConf/add",
          edit: "/lww/oilConf/edit",
          get: "/lww/oilConf/get",
          delete: "/lww/oilLabel/delete",
          addLabel: "lww/oilLabel/add"
       },
    }
  },

  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = {"X-Access-Token":token};
    this.add();
  },
  computed: {
      uploadAction:function () {
        return this.url.fileUpload;
      }
  },
    methods: {
      // 获取输入提示信息
      // autoInput(){
      //   var keywords = document.getElementById("input").value;
      //   AMap.plugin('AMap.Autocomplete', function(){
      //     // 实例化Autocomplete
      //     var autoOptions = {
      //       city: '全国'
      //     }
      //     var autoComplete = new AMap.Autocomplete(autoOptions);
      //     autoComplete.search(keywords, function(status, result) {
      //       // 搜索成功时，result即是对应的匹配数据
      //       var node = new PrettyJSON.view.Node({
      //           el: document.querySelector("#input-info"),
      //           data: result
      //       });
      //     })
      //   })
      // },
      showInput () {
        this.inputVisible = true
        this.$nextTick(function () {
          this.$refs.input.focus()
        })
      },
      handleInputChange (e) {
        this.inputValue = e.target.value
      },
      handleInputConfirm() {
        let that = this;
        const inputValue = this.inputValue
        if (inputValue) {
            if(!this.model.id) {
              that.$message.warning("请先保存基本信息!");
            } else {
              httpAction(this.url.addLabel,{oilConfId: that.model.id, oilLabel: inputValue},'post').then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  httpAction(that.url.get, null, 'get').then((res)=>{
                    if(res.success){
                      that.edit(res.result);
                    }else{
                    }
                  }).finally(() => {
                  })
                }else{
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
                that.close();
              })
            }
        }
        Object.assign(this, {
          inputVisible: false,
          inputValue: '',
        })
      },
      closeOilLabel(id) {
        this.handleDelete(id);
      },
      add () {
        this.picUrl = "";
        httpAction(this.url.get, null, 'get').then((res)=>{
          if(res.success){
            this.edit(res.result);
          }else{
          }
        }).finally(() => {
        })
      },
      edit (record) {
        let that = this;
        that.form.resetFields();
        that.userId = record.id;
        that.visible = true;
        if(record.hasOwnProperty("id")){
          this.picUrl = "Has no pic url yet";
        }
        that.model = Object.assign({}, record);
        that.$nextTick(() => {
          that.form.setFieldsValue(pick(this.model,'lat','lng', 'oilAddress', 'phone', 'img'))
        });
      },
      // 文件上传预览 start
      beforeUpload: function(file){
        var fileType = file.type;
        if(fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          return false;
        }
        //TODO 验证文件大小
      },
      handleChange (info) {
        this.picUrl = "";
        if (info.file.status === 'uploading') {
          this.uploadLoading = true;
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response;
          this.uploadLoading = false;
          if(response.success){
            this.model.img = response.message;
            this.picUrl = "Has no pic url yet";
          }else{
            this.$message.warning(response.message);
          }
        }
      },
      getAvatarView(){
        return this.url.imgerver +"/"+ this.model.img;
      },
      handleResetP() {
        let that = this;
        that.model.lat = '';
        that.model.lng = '';
        that.$nextTick(() => {
          that.form.setFieldsValue(pick(that.model,'lat','lng', 'oilAddress', 'phone', 'img'))
        });
      },
      getP(p) {
        let that = this;
        that.model.lat = p.lat;
        that.model.lng = p.lng;
        that.$nextTick(() => {
          that.form.setFieldsValue(pick(that.model,'lat','lng', 'oilAddress', 'phone', 'img'))
        });
      },
      saveOilConf() {
        const that = this;
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            
            var params = {
              oilType: this.model.oilType,
              oilNo: this.model.oilNo,
              id: this.model.id
            };
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                httpAction(that.url.get, null, 'get').then((res)=>{
                  if(res.success){
                    that.edit(res.result);
                  }else{
                  }
                }).finally(() => {
                })
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      }
    }
  }
</script>
<style scoped>
  /* @import '~@assets/less/common.less' */

</style>